var regDS = null;
var regCyAC = null;
var companySerach_yui_table_instance = null;



var fldmap = [ {fid : "username", required : true},
               {fid : "password",required : true},
               {fid : "fname", required : true},
               {fid : "lname", required : true},
               {fid : "addr_line1", required : true},
               {fid : "city", required : true},
               {fid : "state", required : true},
               {fid : "zip", required : true}
              ];

var fldmapCompany = [ {fid : "reg_companyName", required : true},
               {fid : "reg_lob",required : true},
               {fid : "reg_CompanyContact", required : true},
               {fid : "reg_compAddressLine1", required : true},
               {fid : "reg_compState", required : true},
               {fid : "reg_compZip",required : true},
               {fid : "reg_areaCodePhone", required : true},
               {fid : "reg_areaCodePhoneNumber", required : true},
               {fid : "reg_compPaymentTerms", required : true}
              ];
		


function tn_registerUser(){
	var regXfer = {
			userName : "",
			password : "",
			fname: "",
			lname: "",
			companyName: "",
			companyTaxId : "",
			companySsn: "",
			addressLine1 : "",
			addressLine2 : "",
			city: "",
			state : "",
			zip : "",
			workPhone : "",
			extension : "",
			fax: "",
			email : "",
			buyer : false,
			supplier: false,
			country:"",
			deliveryInfo:""
			
	};
	
	regXfer.userName = dwr.util.getValue("username");
	regXfer.password = dwr.util.getValue("password");
	regXfer.salutation = document.getElementById("reg_salutation").options[document.getElementById("reg_salutation").selectedIndex].value;
	regXfer.fname = dwr.util.getValue("fname");
	regXfer.lname = dwr.util.getValue("lname");
	regXfer.addressLine1 = dwr.util.getValue("addr_line1");
	regXfer.addressLine2 = dwr.util.getValue("addr_line2");
	regXfer.city = dwr.util.getValue("city");
	regXfer.state = dwr.util.getValue("state");
	regXfer.zip = dwr.util.getValue("zip");
	regXfer.workPhone = dwr.util.getValue("areaPhone")+dwr.util.getValue("phoneNumber");
	regXfer.fax = dwr.util.getValue("areaFax")+dwr.util.getValue("faxNumber");
	regXfer.email = dwr.util.getValue("username_confirm");
	regXfer.country = dwr.util.getValue("country");
	regXfer.deliveryInfo = dwr.util.getValue("deliveryNote");
	
	var validationCallMetaData = { 
			  callback:isRegistrationValid, 
			  exceptionHandler: exception_generic_handler,
			  timeout: 100000,
			  errorHandler:  exception_generic_handler
	};
	
	DWR_Validation.validateRegistration(regXfer, validationCallMetaData);
	
	if(isUserRegistrationDetailsValid == true){
//		alert('Registration details valid... \nRegistering user in YSN.. ');
		var dwrCallMetaData = { 
				  callback:tn_cb_registerUser_success, 
				  exceptionHandler: exception_generic_handler,
				  timeout: 100000,
				  errorHandler:  exception_generic_handler
		};
		
		DWR_Register.registerUser(regXfer,dwrCallMetaData);
	}
}

var isUserRegistrationDetailsValid = false;
function isRegistrationValid(dwrResponse) {
//	alert('isRegistrationValid Message : \n ' + dwrResponse.objRespOrError);
	if(dwrResponse.respCode == 0){
		isUserRegistrationDetailsValid = true;
		return;
	} else {
		isUserRegistrationDetailsValid = false;
		showErrorsOnRegForm(dwrResponse);
	}
}

function showErrorsOnRegForm(dwrResponse){
	// TODO handle displaying this as required.
	alert('Please correct following details : \n' + dwrResponse.objRespOrError);
}

function tn_registerUser_Original_Adi(){
	tn_registerCheckUserId(); // If user click on register button multiple time.
	if(!tn_reg_validate()){
		return false;
	}

	var regXfer = {
			userName : "",
			password : "",
			fname: "",
			lname: "",
			companyName: "",
			companyTaxId : "",
			companySsn: "",
			addressLine1 : "",
			addressLine2 : "",
			city: "",
			state : "",
			zip : "",
			workPhone : "",
			extension : "",
			fax: "",
			email : "",
			buyer : false,
			supplier: false,
			country:"",
			deliveryInfo:""
			
	};
	
	regXfer.userName = dwr.util.getValue("username");
	regXfer.password = dwr.util.getValue("password");
	regXfer.salutation = document.getElementById("reg_salutation").options[document.getElementById("reg_salutation").selectedIndex].value;
	regXfer.fname = dwr.util.getValue("fname");
	regXfer.lname = dwr.util.getValue("lname");
	regXfer.addressLine1 = dwr.util.getValue("addr_line1");
	regXfer.addressLine2 = dwr.util.getValue("addr_line2");
	regXfer.city = dwr.util.getValue("city");
	regXfer.state = dwr.util.getValue("state");
	regXfer.zip = dwr.util.getValue("zip");
	regXfer.workPhone = dwr.util.getValue("areaPhone")+dwr.util.getValue("phoneNumber");
	regXfer.fax = dwr.util.getValue("areaFax")+dwr.util.getValue("faxNumber");
	regXfer.email = dwr.util.getValue("username_confirm");
	regXfer.country = dwr.util.getValue("country");
	regXfer.deliveryInfo = dwr.util.getValue("deliveryNote");
	
	
	
	
	var dwrCallMetaData = { 
			  callback:tn_cb_registerUser_success, 
			  exceptionHandler: exception_generic_handler,
			  timeout: 100000,
			  errorHandler:  exception_generic_handler
	};
	
	DWR_Register.registerUser(regXfer,dwrCallMetaData);
}

function tn_registerCompany(userId){
	if(!Company()){
	alert("Please fill all required field");
	return false;
	}
	
	var regXfer = {
			 companyName : "",
			 companyTaxId : "",
			 companySsn : "" ,
			 companyId : "",
			 companyLOB : "",
			 companyContact : "",
			 companyaddressLine1 : "",
			 companyaddressLine2 : "",
			 companyCity : "",
			 companyState : "",
			 companyZip : "",
			 companyCountry : "",
			 companyPhoneNumber : "",
			 companyFaxNumber : "",
			 companyEmail : "",
			 companyURL : "",
			 companyCurrency : "",
			 companyPaymentTerms : ""
			
	};
	
	
	
	regXfer.companyName = dwr.util.getValue("reg_companyName");
	regXfer.companyLOB = dwr.util.getValue("reg_lob");
	regXfer.companyTaxId = dwr.util.getValue("reg_taxId");
	regXfer.companySsn = dwr.util.getValue("reg_SSN");
	regXfer.companyaddressLine1 = dwr.util.getValue("reg_compAddressLine1");
	regXfer.companyaddressLine2 = dwr.util.getValue("reg_compAddressLine2");
	regXfer.companyContact = dwr.util.getValue("reg_CompanyContact");
	regXfer.companyCity = dwr.util.getValue("reg_compCity");
	regXfer.companyState = dwr.util.getValue("reg_compState");
	regXfer.companyZip = dwr.util.getValue("reg_compZip");
	regXfer.companyPhoneNumber = dwr.util.getValue("reg_areaCodePhone")+dwr.util.getValue("reg_areaCodePhoneNumber");
	regXfer.companyFaxNumber = dwr.util.getValue("reg_areaCodeFax")+dwr.util.getValue("reg_areaCodeFaxNumber");
	regXfer.companyEmail = dwr.util.getValue("reg_compEmail");
	regXfer.companyCountry = dwr.util.getValue("reg_compCountry");
	regXfer.companyURL = dwr.util.getValue("reg_compURL");
	regXfer.companyCurrency = dwr.util.getValue("reg_compCurrency");
	regXfer.otherRegId = dwr.util.getValue("company_reg_idType");
	regXfer.otherRegvalue = dwr.util.getValue("company_reg_idValue");
	regXfer.companyPaymentTerms = dwr.util.getValue("reg_compPaymentTerms");
	
	
	var dwrCallMetaData = { 
			  callback:tn_cb_registerCompany_success, 
			  exceptionHandler: exception_generic_handler,
			  timeout: 100000,
			  errorHandler:  exception_generic_handler
	};
	
	DWR_Register.registerCompany(userId,regXfer,dwrCallMetaData);
}


function tn_cb_registerUser_success(dwrResponse){
	if(dwrResponse.respCode == 0){
		//we're good, show some good message.
		//u_safeSetText_ChangeClass('register_status', 'Registration completed successfully.', 'successText');
		//$("validationPlaceHolder").innerHTML = "";
		alert('Registration completed successfully. Please check your email to confirm Registration.');
		//$("validationPlaceHolder").innerHTML = "<b>Registration completed successfully. Please check your email to confirm Registration.</b>";
		if($("input_2") && $("input_2") != null){
			$("input_2").disabled = true;
		}
	}else{
		//show error.
		//u_safeSetText_ChangeClass('register_status', 'Registration failed.', 'errorText');
		alert('Registration Error. Contact Admin');
	}
}

function tn_cb_registerCompany_success(dwrResponse){
	if(dwrResponse.respCode == 0){
		//we're good, show some good message.
		//u_safeSetText_ChangeClass('register_status', 'Registration completed successfully.', 'successText');
		
		var isNavToLogin = confirm('Registration of Company completed successfully. Do You Want To Login Now?');
		if(isNavToLogin){
			document.location.href = "http://www.atsocii.com/";
		}
	}else{
		//show error.
		//u_safeSetText_ChangeClass('register_status', 'Registration failed.', 'errorText');
		alert('Registration Error. Contact Admin');
	}
}

function tn_registerCheckUserId(){
	var dwrCallMetaData = {
			 callback:tn_cb_checkUserId_success, 
			 exceptionHandler: tn_cb_checkUserId_exception,
			 timeout: 100000,
			 errorHandler:  exception_generic_handler,
			 async:false
	};
	
	DWR_Register.checkUserIdAvailable(dwr.util.getValue('username'),dwrCallMetaData);
	
}
var isUserIdValid = false;
function tn_cb_checkUserId_success(dwrResponse){
	u_safeShowElement('username_avl_status');
	if(dwrResponse.respCode == 0){
		isUserIdValid = true;
	}else{
		isUserIdValid =  false;
	}
}

function tn_cb_checkUserId_exception(excecptionmsg, exception){
	alert(excecptionmsg);
}

function tn_reg_validate(){
	var isvalid = true;
	for(var i=0;i<fldmap.length;i++){
		var fld = fldmap[i];
		if(fld && fld['required']&& isEmptyField(fld['fid'])){
			u_safeSetText_ChangeClass(fld['fid'],'','form-validation-error');
			var fid = fld['fid']
			              try{
			 $(fid+"_error").innerHTML = "This is required field"     
			              }catch(ex){}
			isvalid = false;
		} else{
			//u_safeSetText_ChangeClass(fld['fid'],'','');
			//
		}
	}
	
	
	
	
	if($("username_confirm").value != $("username").value ){
			$("username_confirm_error").innerHTML = "Email and Confirm Email Does not Match"     
			isvalid = false;
	}
	
	if(!isUserIdValid){
		if($("username").value == ""){
			$("username_error").innerHTML = "Email Id is Required"   
		}else{
			$("username_error").innerHTML = "This Email Id Already Registered"    
		}
		isvalid = false;
	}
	
	if(!tn_reg_checkPwdMatch() ){
		
			$("conf_password_error").innerHTML = "Password and Confirm Password Does not Match"    
			isvalid = false;
	}
	
	if(!validatePassword(dwr.util.getValue('password')) ){
		
			$("password_error").innerHTML = "Password must be minimum 8 characters and alphanumeric" 
			isvalid = false;
	}
	
	if(! $("term_conditionFlag").checked ){
		$("validationPlaceHolder").innerHTML = "<b>Please Accept Terms and Condition</b>"
			isvalid = false;
	}
		
	if(!isvalid){
		$("validationPlaceHolder").innerHTML = "<b>Please fill all required field</b>";
		window.scroll(0,75);
	}	
	
	return isvalid;
}







function tn_reg_changeCSSClass(obj){
	if(obj.value != ""){
		u_safeSetText_ChangeClass(obj.id,obj.value,'');
		try{
		u_safeSetText_ChangeClass(obj.id+"_error",obj.innerHTML,'');
		}catch(ex){}
	}
}

function tn_reg_validateCompany(){
	var isvalid = true;
	for(var i=0;i<fldmapCompany.length;i++){
		var fld = fldmapCompany[i];
		if(fld && fld['required']&& isEmptyField(fld['fid'])){
			u_safeSetText_ChangeClass(fld['fid'],'','form-validation-error');
			isvalid = false;
		} else{
			//u_safeSetText_ChangeClass(fld['fid'],'','');
			//
		}
	}
	return isvalid;
}

function tn_reg_checkPwdMatch(){
	var pwd = dwr.util.getValue('password');
	var cpwd = dwr.util.getValue('conf_password');
	if(pwd != cpwd){
		return false;
	}else{
		return true;
	}
	
}
YAHOO.widget.DataTable.Formatter.selectCompanyFormatter  = function(elLiner, oRecord, oColumn, oData) {
	   elLiner.innerHTML = "<a href=\"javascript:select_company_line('"+ oRecord.getId()+"');\"  >Select</a>";
}

var companyColumnDefs = [ 
{key:"radio", width : "40px",label:"Select Company" ,formatter:YAHOO.widget.DataTable.Formatter.selectCompanyFormatter},
{
	key : "companyName",
	label : "Company Name",
	width : "40px"
	
},
{
	key : "lineOfBusiness",
	label : "Line Of Business",
	width : "40px"
	
},

{
	key : "address",
	label : "Address",
	width : "40px"
	
},

{
	key : "city",
	label : "City",
	width : "40px"
	
},

{
	key : "state",
	label : "State",
	width : "40px"
	
},

{
	key : "zip",
	label : "Zip",
	width : "40px"
	
},
{
	key : "phone",
	label : "Phone",
	width : "40px"
	
},
{
	key : "companyId",
	width : "0px",
	hidden: true
	
},{
	key : "adminIdList",
	width : "0px",
	hidden: true
	
}



];









function create_manageCompanySerachTable() {
	if(companySerach_yui_table_instance == null){
		var companyDataSource = new YAHOO.util.DataSource();
		companyDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		 var oConfigs = {
	             paginator: new YAHOO.widget.Paginator({
	                 rowsPerPage: 5
	                 
	             }),
	             initialRequest: "results=504",
	             width: "600px",
	             // we'll leave the actual loading for later
	 			initialLoad:true
	 		
	     };
		
		companySerach_yui_table_instance = new YAHOO.widget.DataTable(
				"comapnySerachDivYUITable",
				companyColumnDefs,
				companyDataSource,
				oConfigs);
		companySerach_yui_table_instance.set("selectionMode", "single");
		companySerach_yui_table_instance.subscribe("rowClickEvent",
				companySerach_yui_table_instance.onEventSelectRow);
		
	}
	
	

	

}
var selectedCompIdForNonAdminReg = null; 
function select_company_line(id){
	
	var record = companySerach_yui_table_instance.getRecordSet().getRecord(id);
	var adminArray =  record.getData("adminIdList");
	var isConfirm = false;
	
	if(adminArray == null || adminArray.length < 2){
		 isConfirm = confirm("Are you sure you want to get Asscoiated to "+ record.getData("companyName") + "?" );
	} else{
		selectedCompIdForNonAdminReg = record.getData("companyId");
		tn_getAdminForComapny(record.getData("companyId"),record.getData("companyName"));
		return;
	}
	
	if(isConfirm){
		tn_associateUserToCompany(record.getData("companyId"));
	}
	
	
}

var selectedCompanyName = "";
function tn_getAdminForComapny(companyId,companyName){
	selectedCompanyName = companyName;
	var config = {
			callback : success_getAdminForComapny,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler	
	};
	
	DWR_Register.getAdminUserForCompany(companyId,config);
}

function success_getAdminForComapny(profileList){
	
	var isConfirmNonAdminUser = false;
	 for(i = 0;i<profileList.objRespOrError.length;i++){
		 $("superuser"+i).innerHTML = profileList.objRespOrError[i].firstName + "&nbsp;"+profileList.objRespOrError[i].lastName +"&nbsp;<a href='javascript:void();'>"+profileList.objRespOrError[i].emailAddress +"</a>";
	 }
	 
	 if(isConfirmNonAdminUser){
			//tn_associateUserToCompany(record.getData("companyId"));
			alert("Sent Reuest For Approval.")
		}
	 
	 $("selectedCompanyNameSpan").innerHTML = selectedCompanyName;
	 
	 $("super_userPanel").style.display = "block";
	 super_userPanel.show();
}

function success_AssociateNonAdminUserToCompany(response){
	if(super_userPanel != null){
		super_userPanel.hide();
	}
	alert("Mail Sent");
}

function tn_sendApproveRequest(){
	var config = {
			callback : success_AssociateNonAdminUserToCompany,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler	
	};
	DWR_Register.associateNonAdminUserToCompany(loggedInUserId, selectedCompIdForNonAdminReg);
}



function success_serachCompany(companyList){
	var records = new Array();
	create_manageCompanySerachTable();
	companySerach_yui_table_instance.deleteRows(0,companySerach_yui_table_instance.getRecordSet().getRecords().length);
	 for(i = 0;i<companyList.objRespOrError.length;i++){
		 var record = companyList.objRespOrError[i];
		 var record1 = {};
		 record1.companyName = record.companyName;
		 record1.lineOfBusiness = record.companyDoingBusinessAs;
		 record1.address = record.addressLine1;
		 record1.city = record.city;
		 record1.state = record.state;
		 record1.zip = record.zip;
		 record1.phone = record.phone;
		 record1.companyId = record.companyId;
		 record1.adminIdList = record.companyProfileAdmins;
		 companySerach_yui_table_instance.addRow(record1);
		 records.push(record1);
		 
	 }
	 companySerach_yui_table_instance.render();
	
	
}

function tn_comapnyRegister_serachCompany(){
	if($("search_companyName").value != ""){
		searchObj = "";
		var config = {
				callback : success_serachCompany,
				exceptionHandler : exception_generic_handler,
				timeout : 100000,
				errorHandler : exception_generic_handler	
		};
		searchObj = $("search_companyName").value;
		DWR_Register.searchCompany(searchObj,config);
	}else{
		alert("Please Enter Company Name");
	}
}

function tn_associateUserToCompany(companyId){
	searchObj = "";
	var config = {
			callback : success_associateUserToCompany,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler	
	};
	searchObj = $("search_companyName").value
	DWR_Register.associateUserToCompany(loggedInUserId,companyId,config);
}

function success_associateUserToCompany(responseObj){
	if(responseObj.respCode == 0){
		//alert("User Successfully assciated with Company. You have following Roles Super User For this company");
		super_userSucceeReg.show();
	}
}


function reg_openTnc(){
	window.open('http://' + top.location.host + '/jsp/atsociiTnC.html','tncWindow','top=200,width=400,height=200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=no'); 
};

/*
Password Validator 0.1
(c) 2007 Steven Levithan <stevenlevithan.com>
MIT License
*/

function validatePassword (pw) {
// default options (allows any password)
var o = {
	lower:    0,
	upper:    0,
	alpha:    0, /* lower + upper */
	numeric:  1,
	special:  0,
	length:   [8, Infinity],
	custom:   [ /* regexes and/or functions */ ],
	badWords: [],
	badSequenceLength: 0,
	noQwertySequences: true,
	noSequential:      true
};

/*for (var property in options)
	o[property] = options[property];*/

var	re = {
		lower:   /[a-z]/g,
		upper:   /[A-Z]/g,
		alpha:   /[A-Z]/gi,
		numeric: /[0-9]/g,
		special: /[\W_]/g
	},
	rule, i;

// enforce min/max length
if (pw.length < o.length[0] || pw.length > o.length[1])
	return false;

// enforce lower/upper/alpha/numeric/special rules
for (rule in re) {
	if ((pw.match(re[rule]) || []).length < o[rule])
		return false;
}

// enforce word ban (case insensitive)
for (i = 0; i < o.badWords.length; i++) {
	if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1)
		return false;
}

// enforce the no sequential, identical characters rule
if (o.noSequential && /([\S\s])\1/.test(pw))
	return false;

// enforce alphanumeric/qwerty sequence ban rules
if (o.badSequenceLength) {
	var	lower   = "abcdefghijklmnopqrstuvwxyz",
		upper   = lower.toUpperCase(),
		numbers = "0123456789",
		qwerty  = "qwertyuiopasdfghjklzxcvbnm",
		start   = o.badSequenceLength - 1,
		seq     = "_" + pw.slice(0, start);
	for (i = start; i < pw.length; i++) {
		seq = seq.slice(1) + pw.charAt(i);
		if (
			lower.indexOf(seq)   > -1 ||
			upper.indexOf(seq)   > -1 ||
			numbers.indexOf(seq) > -1 ||
			(o.noQwertySequences && qwerty.indexOf(seq) > -1)
		) {
			return false;
		}
	}
}

// enforce custom regex/function rules
for (i = 0; i < o.custom.length; i++) {
	rule = o.custom[i];
	if (rule instanceof RegExp) {
		if (!rule.test(pw))
			return false;
	} else if (rule instanceof Function) {
		if (!rule(pw))
			return false;
	}
}

// great success!
return true;
}

function lg_sendForgotPasswordMail(){
	var userId = $("forgot_userName").value
	//dwrConfObj = "";
	var dwrConfObj = {
			callback : success_sendForgotPasswordMail,
			exceptionHandler : fail_sendForgotPasswordMail,
			timeout : 100000,
			errorHandler : exception_generic_handler	
	};
	
	DWR_Register.sendForgotPasswordMail(userId,dwrConfObj);
}

function success_sendForgotPasswordMail(respString){
	hideforgotPasswordPanel();
	alert("An email has been sent to the registered email id. Please click on the link in the email to reset your password.");
}

function fail_sendForgotPasswordMail(respString){
	hideforgotPasswordPanel();
	alert("Error Sending Mail.");
}


function lg_resetpwd(){
	if(!tn_reg_checkPwdMatch() ){
		$("validationPlaceHolder").innerHTML = "<b>Password and Confirm Password Does not Match</b>"
			isvalid = false;
	}else if(!validatePassword(dwr.util.getValue('password')) ){
		$("validationPlaceHolder").innerHTML = "<b>Password must be minimum 8 characters and alphanumeric.</b>"
			isvalid = false;
	}else{
		document.getElementById('reset_form').submit();
	}
}

function tn_regToggle(){
	if($("term_conditionFlag").checked){
		
		$("registerButton").disabled = false;
	} else{
		$("registerButton").disabled = true;
	}
}

function tn_navToLogin(){
	document.location.href="http://www.atsocii.com/";
}

